package com.sec.android.app.myfiles.feature.cloud;

import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;

import com.sec.android.app.myfiles.log.Log;

/**
 * Created by jaebae on 2016-01-29.
 */
public class CursorObserver extends ContentObserver {
    private Cursor mCursor;
    private OnCursorChanged mCallback;
    private int mId;

    private static final int INTERVAL = 300;

    private static int sCurObserverId = 0;

    public interface OnCursorChanged {
        void onCursorChanged(CursorObserver from);
    }

    public CursorObserver(Handler handler, OnCursorChanged callback) {
        super(handler);
        mCallback = callback;
        mId = sCurObserverId++;
    }

    public int getId() {
        return mId;
    }

    public void start(Cursor cursor) {
        if (cursor != null && mCursor == null) {
            Log.d(this, "start");
            cursor.registerContentObserver(this);
            mCursor = cursor;
        }
    }

    public void stop() {
        Log.d(this, "stop");
        if (mCursor != null) {
            mCursor.unregisterContentObserver(this);
            mCursor.close();
            mCursor = null;
        }
    }

    @Override
    public void onChange(boolean selfChange) {
        Log.d(this, "onChange()");
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, INTERVAL);

    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Log.d(CursorObserver.this, "mCallback.onCursorChanged");
            if (mCallback != null) {
                mCallback.onCursorChanged(CursorObserver.this);
            }
            return true;
        }
    });
}
